package com.lujianfei.babymilkmemory.ui.history

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.gestures.detectTransformGestures
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Divider
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalBottomSheet
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.lifecycle.ViewModelProvider
import coil.compose.AsyncImage
import com.lujianfei.babymilkmemory.ui.theme.BabyMilkMemoryTheme
import com.lujianfei.babymilkmemory.utils.IntentUtils
import com.lujianfei.babymilkmemory.utils.MyLogger


/**
 * Author: lujianfei
 * Date: 2025/2/13 18:14
 * Description:
 */

class HistoryActivity : ComponentActivity() {

    companion object {
        const val TAG = "HistoryActivity"
        const val INTENT_TYPE = "type"
        fun start(context: Context, type: Int) {
            context.startActivity(
                Intent(context, HistoryActivity::class.java)
                    .putExtra(INTENT_TYPE, type)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            )
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            BabyMilkMemoryTheme {
                Scaffold(topBar = {
                    TopAppBar(title = {
                        Text(text = "历史记录", color = MaterialTheme.colorScheme.onPrimary)
                    })
                }) { padding ->
                    Content(modifier = Modifier.padding(padding))
                }
            }
        }
    }

    @Composable
    fun Content(modifier: Modifier = Modifier) {
        val viewModel = ViewModelProvider(this)[HistoryViewModel::class.java]
        viewModel.type.value = intent.getIntExtra(INTENT_TYPE, 0)
        Box(modifier = modifier.fillMaxSize()) {
            LazyColumn(modifier = Modifier.fillMaxSize()) {
                items(viewModel.list) { item ->
                    HistoryItem(item) {
                        viewModel.deleteData(it)
                    }
                }
            }
            if (viewModel.loading.value) {
                CircularProgressIndicator()
            }

//            IconButton(modifier = Modifier
//                .align(Alignment.BottomEnd)
//                .padding(15.dp), onClick = {
//                viewModel.addData()
//            }) {
//                Icon(Icons.Default.AddCircle, contentDescription = "")
//            }
        }
        LaunchedEffect(Unit) {
            viewModel.load()
        }
    }

    @Composable
    fun HistoryItem(item: HistoryModel, onDelete: (HistoryModel) -> Unit) {
        val viewModel = ViewModelProvider(this)[HistoryViewModel::class.java]
        val showDialog = remember { mutableStateOf(false) }
        val showConfirmDialog = remember { mutableStateOf(false) }
        val showImagePreview = remember { mutableStateOf(false) }
        val mImageUriFromCamera = remember {
            mutableStateOf(Uri.EMPTY)
        }

        val launcherCamera =
            rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                MyLogger.d("ImageAdd", "result.resultCode:${result.resultCode}")
                if (result.resultCode == RESULT_OK) {
                    mImageUriFromCamera.value?.let {
                        viewModel.setImage(item, it, fromAlbum = false)
                    }
                }
            }

        val launcherAlbum =
            rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
                MyLogger.d("ImageAdd", "result.resultCode:${result.resultCode}")
                val clipData = result.data?.clipData
                if (clipData != null) {
                    for (i in 0 until clipData.itemCount) {
                        val uri = clipData.getItemAt(i).uri
                        viewModel.setImage(item, uri, fromAlbum = true)
                    }
                } else {
                    result.data?.data?.let {
                        viewModel.setImage(item, it, fromAlbum = true)
                    }
                }
            }
        if (showDialog.value) {
            BottomMenu(showDialog, showConfirmDialog, onAlbumClick = {
                launcherAlbum.launch(IntentUtils.openAlbumIntent())
            }, onCameraClick = {
                launcherCamera.launch(IntentUtils.openCameraIntent {
                    mImageUriFromCamera.value = it
                })
            })
        }

        if (showConfirmDialog.value) {
            ConfirmDialog(showConfirmDialog, item, onDelete)
        }

        if (showImagePreview.value) {
            ImagePreviewDialog(
                imageUri = item.uri.value,
                onDismiss = { showImagePreview.value = false }
            )
        }


        Column(
            modifier = Modifier
                .fillMaxWidth()
        ) {
            Row(modifier = Modifier
                .padding(15.dp)
                .fillMaxWidth()
                .pointerInput(Unit) {
                    detectTapGestures(
                        onLongPress = {
                            if (item.id > 0) {
                                showDialog.value = true
                            }
                        }
                    )
                },
                horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween
            ) {
                Text(text = item.label, style = MaterialTheme.typography.titleLarge)
                Text(text = item.getDataString(), style = MaterialTheme.typography.titleLarge)
            }

                Row(
                    modifier = Modifier
                        .padding(15.dp)
                        .fillMaxWidth(),
                    horizontalArrangement = androidx.compose.foundation.layout.Arrangement.SpaceBetween
                ) {
                    if (item.uri.value.isNotBlank()) {
                        AsyncImage(
                            model = item.uri.value,
                            contentDescription = "image from uri",
                            modifier = Modifier
                                .size(64.dp)
                                .background(Color.Black)
                                .pointerInput(Unit) {
                                    detectTapGestures(
                                        onTap = {
                                            showImagePreview.value = true
                                        }
                                    )
                                }
                        )
                    }
                    if (item.differ > 0) {
                    Text(text = "", style = MaterialTheme.typography.titleLarge)
                    Text(text = "相隔${item.getDifferString()}", style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.primary)
                }
            }
        }
    }

    @OptIn(ExperimentalMaterial3Api::class)
    @Composable
    private fun BottomMenu(
        openSheet: MutableState<Boolean>,
        showConfirmDialog: MutableState<Boolean>,
        onCameraClick:()->Unit = {},
        onAlbumClick:()->Unit = {},
    ) {
        ModalBottomSheet(
            onDismissRequest = { openSheet.value = false },
            dragHandle = {  // 可省略
                Box(
                    Modifier
                        .fillMaxWidth()
                        .height(8.dp)
                )
            }
        ) {
            Text(
                "请选择操作",
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.padding(16.dp)
            )
            Divider()
            ActionItem("拍照") { /* 操作*/
                onCameraClick()
                openSheet.value = false
            }
            ActionItem("相册") { /* 操作*/
                onAlbumClick()
                openSheet.value = false
            }
            Divider()
            ActionItem("删除") { /* 操作*/
                showConfirmDialog.value = true
                openSheet.value = false
            }
            Divider()
            ActionItem("取消", isDestructive = true) { openSheet.value = false }
        }
    }

    @Composable
    private fun ConfirmDialog(
        showDialog: MutableState<Boolean>,
        item: HistoryModel,
        onDelete: (HistoryModel) -> Unit
    ) {
        AlertDialog(
            onDismissRequest = { showDialog.value = false },
            title = { Text(text = "提示", color = MaterialTheme.colorScheme.onPrimary) },
            text = {
                Text(
                    text = "确认删除 ${item.getDataString()} 的记录?",
                    color = MaterialTheme.colorScheme.onPrimary
                )
            },
            confirmButton = {
                Button(onClick = {
                    onDelete(item)
                    showDialog.value = false
                }) {
                    Text("删除")
                }
            },
            dismissButton = {
                Button(onClick = { showDialog.value = false }) {
                    Text("取消")
                }
            }
        )
    }

    @Composable
    fun ActionItem(
        text: String,
        isDestructive: Boolean = false,
        onClick: () -> Unit
    ) {
        TextButton(
            onClick = onClick,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 4.dp)
        ) {
            Text(
                text,
                color = if (isDestructive) MaterialTheme.colorScheme.onError else MaterialTheme.colorScheme.onPrimary
            )
        }
    }

    @Composable
    private fun ImagePreviewDialog(
        imageUri: String,
        onDismiss: () -> Unit
    ) {
        val scale = remember { mutableStateOf(1f) }
        val offsetX = remember { mutableStateOf(0f) }
        val offsetY = remember { mutableStateOf(0f) }

        Dialog(
            onDismissRequest = onDismiss,
            properties = DialogProperties(
                dismissOnBackPress = true,
                dismissOnClickOutside = true,
                usePlatformDefaultWidth = false
            )
        ) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(Color.Black.copy(alpha = 0.9f))
                    .pointerInput(Unit) {
                        detectTransformGestures { _, pan, zoom, _ ->
                            scale.value *= zoom
                            scale.value = scale.value.coerceIn(0.5f, 3f)
                            
                            offsetX.value += pan.x
                            offsetY.value += pan.y
                        }
                    }
                    .pointerInput(Unit) {
                        detectTapGestures(
                            onDoubleTap = {
                                // 双击重置缩放和位置
                                scale.value = 1f
                                offsetX.value = 0f
                                offsetY.value = 0f
                            }
                        )
                    }
            ) {
                AsyncImage(
                    model = imageUri,
                    contentDescription = "大图预览",
                    modifier = Modifier
                        .fillMaxSize()
                        .graphicsLayer(
                            scaleX = scale.value,
                            scaleY = scale.value,
                            translationX = offsetX.value,
                            translationY = offsetY.value
                        )
                        .clipToBounds()
                )
                
                // 关闭按钮
                TextButton(
                    onClick = onDismiss,
                    modifier = Modifier
                        .align(Alignment.TopEnd)
                        .padding(16.dp)
                ) {
                    Text(
                        "×",
                        color = Color.White,
                        style = MaterialTheme.typography.headlineMedium
                    )
                }
            }
        }
    }
}